<template>
  <div class="register-box">
    <div class="register-box-content">
      <div class="child right-child">
        <div style="width: 100%;height: 100%;">
          <Tabs value="account">
            <Tab-pane label="账号登录" name="account">
              <div class="tab-content">
                <Form ref="userInline" :model="userForm" :rules="userInline">
                  <Form-item prop="userName">
                    <Input size="large" type="text" v-model="userForm.username" placeholder="请输入用户名"
                           @on-enter="handleSubmit('password')"/>
                  </Form-item>
                  <Form-item prop="password">
                    <Input size="large" type="password" v-model="userForm.password" placeholder="请输入密码"
                           @on-enter="handleSubmit('password')"/>
                  </Form-item>
                  <Form-item>
                    <div class="left-right-frame">
                      <div class="flex-none">
                      </div>
                      <div class="flex-none">
<!--                        <span>没有账号?<span>立即注册</span></span>-->
                      </div>
                    </div>
                  </Form-item>
                </Form>

                <Button class="login-btn" size="large" type="primary" @click="handleSubmit('password')"
                        style="width: 100%;">登录
                </Button>
              </div>
            </Tab-pane>
          </Tabs>
        </div>
      </div>
      <div class="child left-child">
        <div style="width: 750px; margin-right: 40px">
          <p class="title">欢迎来到大迈冷链智慧管理平台</p>
          <Divider style="color: #fff; font-size: 12px;"><span>登录注册后您将获得</span></Divider>
          <div style="display: flex; justify-content: space-between; padding: 0 20px;">
            <div style="text-align: left;display: flex; align-items: center;flex-direction: column;">
              <ul>
                <li class="title2">
                  为供应链物流仓储业务提供全链路优质服务
                </li>
                <li class="title2">
                  冷链平台可视化,全方位掌控订单进度
                </li>
              </ul>
            </div>
            <div class="qrCode-container">
              <div class="qrCode">
                <p style="margin: 20px 0">扫码关注“大迈冷链智慧管理小程序(体验版)”</p>
                <img src="../../assets/images/qrCode-test.jpg" width="180" height="180"/>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      width="30vw"
      :visible.sync="customerShow"
      title="选择登录公司"
      z-index="1000"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      @close="customerShow = false">
      <el-row style="height: 40px;line-height: 40px;">
        <el-select
          v-model="selectCustomerId"
          placeholder="请选择"
          style="width: 100%"
          filterable>
          <el-option v-for="item in belongUserCustomerList" :key="item.id" :label="item.customerName" :value="item.id"/>
        </el-select>
      </el-row>
      <template #footer>
        <el-button size="mini" type="warning" @click="customerShow = false">取消</el-button>
        <el-button :loading="customerConfirmLoading" size="mini" type="primary" @click="confirmSelectCustomer">确认
        </el-button>
      </template>
    </el-dialog>

    <el-dialog
      :visible="selectShow"
      width="60vw"
      title="登录选择"
      z-index="1000"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      @close="onClose"
    >
      <el-form ref="selectForm" :model="selectForm" :rules="selectRules" label-width="80px">
        <el-form-item label="登录权限" prop="currentAgentPermission">
          <el-radio-group v-model="selectForm.currentAgentPermission" @input="onChangeSelect">
            <el-radio :label="1">代理商</el-radio>
            <el-radio :label="0">货主</el-radio>
          </el-radio-group>
<!--          <div class="login-tips">请选择您的登录权限，如选择货主权限需选择登录公司！</div>-->
        </el-form-item>
<!--        <el-form-item label="公司选择" prop="customerIds">-->
<!--          <el-select-->
<!--            v-model="selectForm.customerIds"-->
<!--            :disabled="belongUserCustomerList.length === 1 || !!selectForm.currentAgentPermission"-->
<!--            :multiple="!!selectForm.currentAgentPermission"-->
<!--            filterable-->
<!--            style="width: 100%"-->
<!--          >-->
<!--            <el-option-->
<!--              v-for="item in belongUserCustomerList"-->
<!--              :key="item.id"-->
<!--              :value="item.id"-->
<!--              :label="item.customerName"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <el-button size="mini" type="warning" @click="onClose">取消</el-button>
        <el-button size="mini" type="primary" :loading="customerConfirmLoading" @click="onConfirm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import loginApi from '@/api/login.js';
import md5 from 'js-md5';
import _ from 'lodash';
import {mapActions} from 'vuex';
import api from '@/api/login';

export default {
  name: "login",
  data() {
    return {
      selectCustomerId: null,
      belongUserCustomerList: [],
      customerConfirmLoading: false,
      customerShow: false,
      code: '',
      verificateCode: '',
      userForm: {
        userName: '',
        password: '',
        captchaCode: '',
        code: '',
        role: null
      },
      phoneForm: {
        phone: '',
        captchaCode: '',
        smsCode: ''
      },
      userInline: {
        user: [
          {required: true, message: '请填写用户名', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '请填写验证码', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请填写密码', trigger: 'blur'},
          {type: 'string', min: 6, message: '密码长度不能小于6位', trigger: 'blur'}
        ]
      },
      phoneInline: {
        phone: [
          {required: true, message: '请填写手机号', trigger: 'blur'}
        ],
        captchaCode: [
          {required: true, message: '请填写验证码', trigger: 'blur'},
          {type: 'string', min: 4, max: 4, message: '验证码长度6位', trigger: 'blur'}
        ],
        smsCode: [
          {required: true, message: '请填写短信验证码', trigger: 'blur'},
          {type: 'string', min: 6, max: 6, message: '短信验证码长度6位', trigger: 'blur'}
        ]
      },
      sendSmsCodeBtn: {
        disabled: false,
        text: '发送短信',
        counter: 60
      },
      rememberPassword: false,
      selectShow: false,
      selectForm: {},
      selectRules: {
        currentAgentPermission: [{required: true, message: '请选择登录权限', trigger: ['blur', 'change']}],
        customerIds: [{required: true, message: '请选择登录公司', trigger: 'change'}]
      }
    }
  },
  methods: {
    ...mapActions('user', [
      'setToken',
      'setUserInfo'
    ]),
    changeCode(code) {
      this.code = code;
    },
    onOpenSelect() {
      this.selectForm = {currentAgentPermission: 1};
      this.onChangeSelect(1);
      this.selectShow = true;
    },
    onChangeSelect(value) {
      if (value) {
        this.$set(this.selectForm, 'customerIds', this.belongUserCustomerList.map(i => i.id));
      } else if (this.belongUserCustomerList.length !== 1) {
        this.$set(this.selectForm, 'customerIds', '');
      }
    },
    onClose() {
      this.selectShow = false;
    },
    onConfirm() {
      this.$refs.selectForm.validate(valid => {
        if (!valid) return;
        if (this.selectForm.currentAgentPermission == 1) {
          window.localStorage.setItem('belongUserCustomerList', JSON.stringify(this.belongUserCustomerList));
        }
        const params = {...this.userForm, ...this.selectForm, loginUserType: 1};
        params.password = md5(this.userForm.password).toUpperCase();
        ['number', 'string'].includes(typeof params.customerIds) && (params.customerIds = [this.selectForm.customerIds]);
        this.confirm(params);
      });
    },
    confirmSelectCustomer() {
      if (!this.selectCustomerId) {
        this.$Message.error('请选择客户');
        return;
      }
      this.userForm.customerIds = [];
      let body = _.cloneDeep(this.userForm);
      body.customerIds.push(this.selectCustomerId);
      body.password = md5(this.userForm.password).toUpperCase();
      body.loginUserType = 1;
      this.confirm(body);
    },
    confirm(body) {
      this.customerConfirmLoading = true;
      loginApi.loginSys(body).then(async ({data}) => {
        if (data.returnCode === 200) {
          const token = data.returnData.returnData['id_token'];
          if (token) {
            this.setToken(token);
            let {data} = await api.getUserInfo()
            if (data.returnCode === 200) {
              this.setUserInfo(data.returnData);
              this.$router.push({name: data.returnData.userName === 'customs' ? 'monitor-customer-map' : 'WorkbenchIndex'});
            } else {
              this.$Message.error(data.returnMsg);
            }
          }
        } else {
          this.$Message.error(data.returnMsg);
        }
      }).finally(() => {
        this.customerConfirmLoading = false;
      })
    },
    async handleSubmit(type) {
      if (type === 'password') {
        this.$refs.userInline.validate(valid => {
          if (valid) {
            loginApi.getCustomerByUserName(this.userForm.username).then(async ({data}) => {
              if (data.returnCode === 200) {
                this.belongUserCustomerList = data.returnData;
                if (this.belongUserCustomerList.length == 0) {
                  this.$Message.error('当前登录用户无所属客户');
                  return;
                }
                if (this.belongUserCustomerList.some(i => i.agentPermission === 1)) {
                  this.onOpenSelect();
                  return;
                }
                if (this.belongUserCustomerList.length == 1) {
                  this.selectCustomerId = this.belongUserCustomerList[0].id
                  this.confirmSelectCustomer();
                } else {
                  this.customerShow = true;
                }
              } else {
                this.$Message.error(data.returnMsg);
              }
            })
          }
        });
      } else {
        this.$refs.phoneInline.validate(valid => {
          if (valid) {
            let body = {
              phone: this.userForm.phone,
              verificationCode: this.userForm.smsCode
            }
            loginApi.currentAgentPermissionorizePhone(body).then(({data}) => {
              if (data.returnCode === 200) {
                const token = data.returnData.returnData['id_token'];
                if (token) {
                  this.setToken(token);
                  this.$router.push({name: 'WorkbenchIndex'});
                }
              } else {
                this.$Message.error(data.returnMsg);
              }
            })
          }
        })
      }
    }
  }
}
</script>

<style lang="less">
.register-box {
  .ivu-tabs-nav .ivu-tabs-tab {
    font-size: 20px !important;
  }

  .ivu-tabs-nav .ivu-tabs-tab-active {
    font-size: 21px !important;
    color: #000000 !important;
    font-weight: bold;
  }
}
</style>
<style scoped lang="less">
.register-box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  position: relative;
  background-repeat: no-repeat;
  background-size: cover;
  background-image: url(../../assets/images/bg.png);

  .register-box-content {
    width: 90%;
    display: flex;
    justify-content: space-around;
    position: relative;
  }
}

.child {
  width: 30%;
  min-width: 425px;
  max-width: 500px;
  border-radius: 10px;
  background: #ffffff;
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, .04);
  padding: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: start;
}

.left-child {
  color: #fff;
  background-color: rgba(255, 255, 255, 0);
  box-shadow: none;
  text-align: center;

  .title {
    //font-family: "SourceHanSansCN-Medium",serif;
    font-size: 30px;
    font-weight: 700;
  }

  .title2 {
    font-size: 14px;
    margin-top: 15px;
  }

  .qrCode-container {
    width: 400px;
    height: auto;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 20px;

    .qrCode {
      width: 70%;
      height: 270px;
      border-radius: 20px;
      background-color: rgba(66, 116, 203, 1);
    }
  }
}

.right-child {
  padding-left: 50px;
  padding-right: 50px;
  .login-btn {
    margin-top: 30px;
    background-color: #4F68E8;
    position: relative;
  }

  .login-btn:hover {
    opacity: .9;
  }
}

.tab-content {
  padding-top: 50px;
  height: 100%;
}

.left-right-frame {
  display: flex;
  justify-content: space-between;
}

.captcha-code {
  height: 36px;
  width: 90px;
  border: solid 1px #eee;
}

.login-tips {
  color: red;
  display: inline-block;
  margin-left: 32px;
}
</style>
